import React, { Component, } from 'react';
import './index.less'
import { base, } from 'nc-lightapp-front';
const {NCButton, NCCheckbox,} = base;

class SSCTransfer extends Component {
  constructor(props) {
    super(props)
    this.state = {
      leftCheckAll: false, // 左侧全选
      rightCheckAll: false, // 右侧全选
      leftCheck: false, // 左侧有选中
      rightCheck: false, // 右侧有选中
      sourceTreeCheckData: [], // 数据源 选中节点
      targetTreeCheckData: [], // 目标树 选中节点
    }
  }

  // 初始化
  initSourceTree = () => {
    this.props.syncTree.setSyncTreeData('sourceTree', this.props.dataSource,)
    this.props.syncTree.setSyncTreeData('targetTree', [],)
    this.setState({
      leftCheckAll: false,
      rightCheckAll: false,
      leftCheck: false,
      rightCheck: false,
    })
  }

  // 左侧全选
  leftCheckBoxChange = leftCheckAll => {
    const {
      props: {
        dataSource,
        syncTree: { setNodeChecked, },
      },
    } = this

    const sourceTreeCheckData = []
    if (leftCheckAll) {
      setSourceTreeCheckData(dataSource, sourceTreeCheckData)
    }

    this.setState({
      leftCheckAll, 
      leftCheck: leftCheckAll,
      sourceTreeCheckData,
    })

    if (leftCheckAll) {
      const pks = []
      setCheck(dataSource, pks)
      setNodeChecked('sourceTree', pks)
    } else {
      setNodeChecked('sourceTree', [])
    }
  }

  // 左树选择回调
  onSourceTreeCheckEve = (props, checkedKeys, { checked, checkedNodes, node, event }) => {
    this.setState({
      leftCheck: checkedNodes.length ? true : false,
      sourceTreeCheckData: checkedNodes,
      leftCheckAll: false,
    })
  }

  // 选中右移
  moveRight = () => {
    const {
      state: {sourceTreeCheckData,},
      props: {
        syncTree: {setSyncTreeData, createTreeData,}
      }
    } = this

    const selectNodes = sourceTreeCheckData.map(each => each.props), toBuildTreeNodes = []
    let index = -1
    while(++index < selectNodes.length) {
      this.completePNode(selectNodes[index], toBuildTreeNodes)
    }
    
    const targetTreeData = createTreeData(this.copySelectNodes(toBuildTreeNodes))
    setSyncTreeData('targetTree', targetTreeData)
  }

  // 右移时拷贝选中节点
  copySelectNodes = nodes => {
    let index = -1, result = []
    while (++index < nodes.length) {
      const newNode = {}
      for (let attr in nodes[index]) newNode[attr] = nodes[index][attr]
      newNode.children = null
      result.push(newNode)
    }
    return result
  }

  // 补全父节点
  completePNode = (node, result) => {
    if (!this.hasCurNode(node, result)) {
      result.push(node)
    }
    const pNode = this.props.syncTree.getSyncTreeValue('sourceTree', node.pid)
    if (pNode) {
      this.completePNode(pNode, result)
    }
  }
  // 判断是否已push当前树节点
  hasCurNode = (node, result) => {
    let index = -1
    while(++index < result.length) {
      if (node.refpk === result[index].refpk) return true // 重复
    }
    return false // 未添加
  }

  // 全部右移
  moveRightAll = () => {
    const result = []
    this.deepCopyDataSource(this.props.dataSource, result)
    this.props.syncTree.setSyncTreeData('targetTree', result)
  }

  // 深度拷贝dataSource
  deepCopyDataSource = (data, ret) => {
    let index = -1
    while (++index < data.length) {
      const newNode = {}
      for (let attr in data[index]) {
        if (attr === 'children') {
          newNode[attr] = data[index][attr] ? [] : null
        } else {
          newNode[attr] = data[index][attr]
        }
      }
      ret.push(newNode)
      if (data[index].children && data[index].children.length) {
        this.deepCopyDataSource(data[index].children, newNode.children)
      }
    }
  }

  // 右侧全选
  rightCheckBoxChange = rightCheckAll => {
    const {
      props: {
        syncTree: { setNodeChecked, getSyncTreeValue, },
      },
    } = this

    const targetTreeData = getSyncTreeValue('targetTree')

    this.setState({
      rightCheckAll, 
      rightCheck: rightCheckAll,
      targetTreeCheckData: targetTreeData,
    })
    
    if (rightCheckAll) {
      const pks = []
      setCheck(targetTreeData, pks)
      setNodeChecked('targetTree', pks)
    } else {
      setNodeChecked('targetTree', [])
    }
  }

  // 右树选择回调
  onTargetTreeCheckEve = (props, checkedKeys, { checked, checkedNodes, node, event }) => {
    this.setState({
      rightCheck: checkedNodes.length ? true : false,
      targetTreeCheckData: checkedNodes.map(each => each.props),
      rightCheckAll: false,
    })
  }

  // 选中左移
  moveLeft = () => {
    const { delNodeSuceess, setNodeChecked, } = this.props.syncTree
    setNodeChecked('targetTree', [])
    const pks = []
    setCheck(this.state.targetTreeCheckData, pks, true)
    const toDelPks = [...new Set(pks.filter(pk => !!pk))]
    toDelPks.forEach(each => {
      delNodeSuceess('targetTree', each)
    })
    this.setState({
      targetTreeCheckData: [],
      rightCheckAll: false,
    })
  }

  // 全部左移
  moveLeftAll = () => {
    const { setSyncTreeData, setNodeChecked, } = this.props.syncTree
    setNodeChecked('targetTree', [])
    setSyncTreeData('targetTree', [])
    this.setState({
      targetTreeCheckData: [],
      rightCheckAll: false,
    })
  }

  // 重置
  reset = () => {
    // 取消选中
    this.props.syncTree.setNodeChecked('sourceTree', [])
    this.props.syncTree.setNodeChecked('targetTree', [])
    // state
    this.setState({
      leftCheckAll: false,
      rightCheckAll: false,
      leftCheck: false,
      rightCheck: false,
      sourceTreeCheckData: [],
      targetTreeCheckData: [],
    })
  }

  // 获取目标树选中节点pks
  getTargetKeys = () => {
    const targetTreeData = this.props.syncTree.getSyncTreeValue('targetTree'), targetKeys = []
    setCheck(targetTreeData, targetKeys)
    return targetKeys
  }

  render() {

    const {
      titles,
      syncTree: {
        createSyncTree,
      },
    } = this.props
    
    const {
      leftCheckAll,
      rightCheckAll,
      leftCheck,
      rightCheck,
    } = this.state

    const {
      leftCheckBoxChange,
      rightCheckBoxChange,
      onSourceTreeCheckEve,
      onTargetTreeCheckEve,
      moveRight,
      moveRightAll,
      moveLeftAll,
      moveLeft,
    } = this

    return (
      <div id='SSC-transfer'>
        {/* 来源树 */}
        <div className='u-transfer-list u-transfer-list-left'>
          <div className='u-transfer-list-header'>
            <NCCheckbox
              onChange={leftCheckBoxChange}
              checked={leftCheckAll}
            />
            <span className='u-transfer-list-header-title'>{titles[0]}</span>
          </div>
          <div className='u-transfer-list-body u-transfer-list-body-with-search'>
            {createSyncTree({
              treeId: 'sourceTree',
              needSearch: true,
              disabledSearch: false,
              showModal: false,
              showLine: true,
              checkable: true,
              checkStrictly: false,
              onCheckEve: onSourceTreeCheckEve,
              searchType: 'filtration',
            })}
          </div>
        </div>
        {/* 操作按钮 */}
        <div className='u-transfer-operation'>
          {/* 选中右移 */}
          <NCButton
            fieldid="move-right"
            disabled={!leftCheck}
            onClick={moveRight}
          ><span><i className='uf uf-arrow-right'></i></span></NCButton>
          {/* 全部右移 */}
          <NCButton
            fieldid="all-move-right"
            onClick={moveRightAll}
          ><span><i className='uf uf-2arrow-right'></i></span></NCButton>
          {/* 全部左移 */}
          <NCButton
            fieldid="all-move-left"
            // disabled={!rightCheckAll}
            onClick={moveLeftAll}
          ><span><i className='uf uf-2arrow-left'></i></span></NCButton>
          {/* 选中左移 */}
          <NCButton
            fieldid="move-left"
            disabled={!rightCheck}
            onClick={moveLeft}
          ><span><i className='uf uf-arrow-left'></i></span></NCButton>
        </div>
        {/* 目标树 */}
        <div className='u-transfer-list u-transfer-list-right'>
          <div className='u-transfer-list-header'>
            <NCCheckbox
              onChange={rightCheckBoxChange}
              checked={rightCheckAll}
            />
            <span className='u-transfer-list-header-title'>{titles[1]}</span>
          </div>
          <div className='u-transfer-list-body u-transfer-list-body-with-search'>
            {createSyncTree({
              treeId: 'targetTree',
              needSearch: true,
              disabledSearch: false,
              showModal: false,
              showLine: true,
              checkable: true,
              checkStrictly: false,
              onCheckEve: onTargetTreeCheckEve,
              searchType: 'filtration',
            })}
          </div>
        </div>
      </div>
    )
  }
}

// 获取数据pks
function setCheck(dataSource, pks, isMoveLeft = false) {
  for (let item of dataSource) {
    if (isMoveLeft) {
      pks.push(item.refpk)
    } else {
      if(item.isleaf) {
        pks.push(item.refpk)
      }
    }
    if (item.children && item.children.length) {
      setCheck(item.children, pks)
    }
  }
}
// 拷贝节点
function setSourceTreeCheckData(source, target) {
  let index = -1
  while(++index < source.length) {
    const newNode = {}
    for(let attr in source[index]) {
      if (attr === 'children') {
        newNode[attr] = []
      } else {
        newNode[attr] = source[index][attr]
      }
    }
    target.push({props: newNode})
    if (source[index].children && source[index].children.length) {
      setSourceTreeCheckData(source[index].children, target)
    }
  }
}

export default SSCTransfer